package frobagroup.services.backstage.impl;

import com.google.common.collect.ImmutableMap;
import frobagroup.entities.frontEnd.ShoppingCart;
import frobagroup.entities.frontEnd.UserProfile;
import frobagroup.pagination.PageableImpl;
import frobagroup.pagination.Pagination;
import frobagroup.repositories.frontEnd.ShoppingCartRepository;
import frobagroup.repositories.frontEnd.UserProfileRepository;
import frobagroup.services.backstage.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Tinsley on 2018/5/22.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserProfileRepository userProfileRepository;
    @Autowired
    private ShoppingCartRepository shoppingCartRepository;

    @Override
    public Pagination findUserList(String id, Pagination pagination) {
        String sort = Objects.isNull(pagination.getSort()) ? "updateTime" : pagination.getSort();
        PageableImpl pageable = new PageableImpl(pagination.getPageNumber(),pagination.getPageSize(),
                new Sort(Objects.equals(Sort.Direction.DESC.name(),pagination.getDir()) ? Sort.Direction.DESC:Sort.Direction.ASC,sort)
        );
        Page<UserProfile> pages = userProfileRepository.findAll(pageable);

        pagination.setContent(pages.getContent());
        pagination.setTotal(pages.getTotalElements());
        return pagination;
    }

    @Override
    public Map findUserDetail(String uId) {
        UserProfile userProfile = userProfileRepository.findByUId(uId);
        List<ShoppingCart> shoppingCartList = shoppingCartRepository.findByUId(uId);
        return ImmutableMap.of("userProfile",userProfile,"shoppingCartList",shoppingCartList);
    }
}
